package com.csmy.my.center.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.text.DefaultEditorKit.InsertContentAction;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.csmy.my.center.service.UserInfoService;
import com.csmy.my.center.util.CTConstants;
import com.csmy.my.center.util.CTUtils;
import com.csmy.my.center.util.PageModel;
import com.csmy.my.center.util.StringUtil;
import com.csmy.my.center.util.dataconvert.Dto;
import com.csmy.my.center.util.dataconvert.impl.BaseDto;

import common.Logger;

/**
 * 用户管理action
 * @author wgp
 * @see 2013-01-21
 *
 */
@Controller
@Scope("prototype")
public class UserInfoAction extends BaseActionSupport {

	private static final long serialVersionUID = -7494234699032976084L;
	// 日志记录
	Logger log = Logger.getLogger(UserInfoAction.class);
	
	public PageModel pager = new PageModel();
	@Autowired
	private UserInfoService userInfoService;
	
	public static final String USER_LIST = "user_list";// 列表页
	public static final String MEBM_LIST = "mebm_list";// 会员列表页
	public static final String CUST_LIST = "cust_list";// 商户列表页
	public static final String ADD_CUST = "add_cust";// 增加页
	public static final String EDIT_CUST = "edit_cust";// 修改页
	
	public static final String ADD_USER = "add_user";// 增加页
	public static final String EDIT_USER = "edit_user";// 修改页
	public static final String EDIT_MEM = "edit_memeber";// 修改页
	public static final String SEE_USER = "see_user";// 查看
	public static final String CHANGE = "change";// 修改密码页面
	
	public static final String ROLE_LIST = "role_list";// 列表页
	public static final String ADD_ROLE = "role_info";// 增加页
	public static final String EDIT_ROLE = "role_info";// 修改页
	public static final String SET_PERMIT = "set_permit";// 授权
	
	
	public static final String CUST_SERVER_LIST = "server_list";// 列表页
	
	public static final String ERROR = "error";// 错误页面
	
	HttpServletRequest request = ServletActionContext.getRequest();
	HttpServletResponse response = ServletActionContext.getResponse();
	HttpSession session = request.getSession();
	
	/**
	 * 用户列表数据
	 * @return
	 */
	public String getUserInfo() {
		List<Dto> dList = null;
		try {
			//获取参数信息
			Dto dto =  getPraramsAsDto(request);
			String page_query = dto.getAsString("pageQuery");
			String queryParam = dto.getAsString("searchText");
			dto.put("queryParam", queryParam);
			
			dto = getPageDto(dto);
			dList = CTReader.queryForPage("system.getUserInfo", dto);
			if(CTUtils.isNotEmpty(dList)){
				String role_id = "";
				List<Dto> rList = null;
				for (Dto dto2 : dList) {
					dto2.put("user_type",getCodeName("USERTYPE", dto2.getAsString("user_type")));
					role_id = dto2.getAsString("role_id");
					if(CTUtils.isNotEmpty(role_id)){
						role_id = role_id.replaceAll(",", "','");
						Dto bDto = new BaseDto();
						bDto.put("role_id", role_id);
						rList = CTReader.queryForList("role.getRoleByRoleID", bDto);
						dto2.put("role_name",StringUtil.getStrFromList(rList, "role_name", ","));
					}
				}
			}
			
			Integer totalCount = (Integer)CTReader.queryForObject("system.getUserInfoCount", dto);
			pager = getPageModel(dList, dto.getAsInteger("start"), totalCount);
			
			//返回参数到页面
			request.setAttribute("pm", pager);
			request.setAttribute("enabled", dto.getAsString("enabled"));
			request.setAttribute("alisaname", queryParam);
			
			return USER_LIST;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}
	
	/**
	 * 客服列表数据
	 * @return
	 */
	public String getCustServerList() {
		List<Dto> dList = null;
		try {
			//获取参数信息
			Dto dto =  getPraramsAsDto(request);
			String page_query = dto.getAsString("pageQuery");
			String queryParam = dto.getAsString("searchText");
			dto.put("queryParam", queryParam);
			dto.put("user_type", "1");//获取客服信息
			
			dto = getPageDto(dto);
			dList = CTReader.queryForPage("system.getUserInfo", dto);
			if(CTUtils.isNotEmpty(dList)){
				String user_id = "";
				Integer perCount = 0;
				Dto perDto = new BaseDto();
				for (Dto dto2 : dList) {
					user_id = dto2.getAsString("user_id");
					perDto.put("user_id", user_id);
					perDto.put("startDate", "");
					perDto.put("endDate", "");
					perCount = (Integer)CTReader.queryForObject("order.getOrderCountBySUserID", perDto);
					dto2.put("zds", CTUtils.isEmpty(perCount)?0:perCount);
					//处理时间
					String today = CTUtils.getCurDate();//今天
					perDto.put("startDate", today);
					perDto.put("endDate", today);
					perCount = (Integer)CTReader.queryForObject("order.getOrderCountBySUserID", perDto);
					dto2.put("jrds", CTUtils.isEmpty(perCount)?0:perCount);
					
					String last3today = CTUtils.getDateByDay(3, CTConstants.FORMAT_Date);//近三天
					perDto.put("endDate", last3today);
					perCount = (Integer)CTReader.queryForObject("order.getOrderCountBySUserID", perDto);
					dto2.put("j3tds", CTUtils.isEmpty(perCount)?0:perCount);
					
					String last7today = CTUtils.getDateByDay(7, CTConstants.FORMAT_Date);//近七天
					perDto.put("endDate", last7today);
					perCount = (Integer)CTReader.queryForObject("order.getOrderCountBySUserID", perDto);
					dto2.put("j7tds", CTUtils.isEmpty(perCount)?0:perCount);
					
					String last30today = CTUtils.getDateByDay(30, CTConstants.FORMAT_Date);//近三十天
					perDto.put("endDate", last30today);
                    perCount = (Integer)CTReader.queryForObject("order.getOrderCountBySUserID", perDto);
                    dto2.put("j30tds", CTUtils.isEmpty(perCount)?0:perCount);
				}
			}
			
			Integer totalCount = (Integer)CTReader.queryForObject("system.getUserInfoCount", dto);
			pager = getPageModel(dList, dto.getAsInteger("start"), totalCount);
			
			//返回参数到页面
			request.setAttribute("pm", pager);
			request.setAttribute("alisaname", queryParam);
			
			return CUST_SERVER_LIST;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}
	
	/**
	 * 用户列表数据
	 * @return
	 */
	public String getRoleInfo() {
		List<Dto> dList = null;
		try {
			//获取参数信息
			Dto dto =  getPraramsAsDto(request);
			String page_query = dto.getAsString("pageQuery");
			String queryParam = dto.getAsString("searchText");
			dto.put("queryParam", queryParam);
			
			dto = getPageDto(dto);
			dList = CTReader.queryForPage("role.getSystemRole", dto);
			if(CTUtils.isNotEmpty(dList)){
				for (Dto dto2 : dList) {
					dto2.put("role_type",getCodeName("ROLE_TYPE", dto2.getAsString("role_type")));
				}
			}
			
			Integer totalCount = (Integer)CTReader.queryForObject("role.getSystemRoleCount", dto);
			pager = getPageModel(dList, dto.getAsInteger("start"), totalCount);
			
			//返回参数到页面
			request.setAttribute("pm", pager);
			request.setAttribute("alisaname", queryParam);
			
			return ROLE_LIST;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}
	/**
	 * 渠道查询
	 * @return
	 */
	public String getChannel() {
		List<Dto> dList = null;
		try {
			//获取参数信息
			Dto dto =  getPraramsAsDto(request);
			String page_query = dto.getAsString("pageQuery");
			String queryParam = dto.getAsString("searchText");
			dto.put("queryParam", queryParam);
			
			dto = getPageDto(dto);
			
			dList = CTReader.queryForPage("resource.getChannel", dto);
			
			
			Integer totalCount = (Integer)CTReader.queryForObject("system.getUserInfoCount", dto);
			pager = getPageModel(dList, dto.getAsInteger("start"), totalCount);
			
			//返回参数到页面
			request.setAttribute("pm", pager);
			request.setAttribute("enabled", dto.getAsString("enabled"));
			request.setAttribute("alisaname", queryParam);
			
			return "channel_list";
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}
	
	
	/**
	 * 会员列表数据
	 * @return
	 */
	public String getMemberInfo() {
		List<Dto> dList = null;
		try {
			//获取参数信息
			Dto dto =  getPraramsAsDto(request);
			String page_query = dto.getAsString("pageQuery");
			String sort_value = dto.getAsString("order_value");
			String sort_type = dto.getAsString("order_type");
			if (StringUtil.isEmpty(sort_type)) {//默认升序
				sort_type = "asc";
			}
			String queryParam = dto.getAsString("searchText");
			dto.put("queryParam", queryParam);
			
			
			dto = getPageDto(dto);
			dList = CTReader.queryForPage("system.getMemberInfo", dto);
			Integer totalCount = (Integer)CTReader.queryForObject("system.getMemberInfoCount", dto);
			//处理下家数统计
			if(!StringUtil.checkListBlank(dList)){
				Integer ccount = 0;
				for (Dto dto2 : dList) {
					if(CTUtils.isNotEmpty(dto2.getAsString("visit_code"))){
					   ccount = (Integer)CTReader.queryForObject("system.getChildMemebers", dto2);
					   dto2.put("xjs", ccount);
					}else{
					   dto2.put("xjs", "0");
					}
					//处理订单
					Integer ocount = (Integer)CTReader.queryForObject("order.getOrderCountByUserID", dto2);
					dto2.put("dds", ocount);
				}
			}
			//处理统计排序
			if(StringUtil.isNotEmpty(sort_value)){
				if(sort_value.equals("childs")){
				   dList = StringUtil.sortDtoList(dList, "xjs", sort_type);
				}
				if(sort_value.equals("orders")){
				   dList = StringUtil.sortDtoList(dList, "dds", sort_type);
				}
			}
			
			
			pager = getPageModel(dList, dto.getAsInteger("start"), totalCount);
			
			//返回参数到页面
			request.setAttribute("pm", pager);
			request.setAttribute("order_value", sort_value);
			request.setAttribute("order_type", sort_type);
			request.setAttribute("alisaname", queryParam);
			
			return MEBM_LIST;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}
	
	
	/**
	 * 会员列表数据
	 * @return
	 */
	public String getCustomerList() {
		
		List<Dto> dList = null;
		try {
			//获取参数信息
			Dto dto =  getPraramsAsDto(request);
			String page_query = dto.getAsString("pageQuery");
			String queryParam = dto.getAsString("searchText");
			dto.put("queryParam", queryParam);
			
			dto = getPageDto(dto);
			dList = CTReader.queryForPage("resource.getCustomerInfo", dto);
			if(!StringUtil.checkListBlank(dList)){
				for (Dto dto2 : dList) {
					dto2.put("level_name", CTUtils.getCodeName("CULEVEL", dto2.getAsString("level")));
				}
			}
			Integer totalCount = (Integer)CTReader.queryForObject("resource.getCustomerInfoCount", dto);
			pager = getPageModel(dList, dto.getAsInteger("start"), totalCount);
			
			//返回参数到页面
			request.setAttribute("pm", pager);
			request.setAttribute("alisaname", queryParam);
			
			return CUST_LIST;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		
	}
	
	
	/**
	 * 验证商户数据
	 * @return
	 */
	public String checkCustomer() {
		String temp = "";
		Dto dto =  getPraramsAsDto(request);
		String customer_name = dto.getAsString("customer_name");
		dto.put("customer_name", CCharseter(customer_name, "UTF-8"));
		List<Dto> dList = CTReader.queryForList("resource.checkCustomer", dto);
		if(!StringUtil.checkListBlank(dList)){
		   temp = "true";
		}else{
		   temp = "false";
		}
		
		return temp;
	}
	
	/**
	 * 增加角色信息
	 * @return
	 */
	public String addRole() {
	    //获取下拉数据
		Dto dto = getPraramsAsDto(request);
		request.setAttribute("typeList", CTUtils.getCodeList("ROLE_TYPE"));
		request.setAttribute("ctype", "add");
		request.setAttribute("roleInfo", new BaseDto());
		return ADD_ROLE;
	}
	
	/**
	 * 修改角色信息
	 * @return
	 */
	public String editRole() {
		//获取当前参数
		Dto dto = getPraramsAsDto(request);
		request.setAttribute("ctype", "edit");
		request.setAttribute("typeList", CTUtils.getCodeList("ROLE_TYPE"));
		Dto roleInfo = (Dto)CTReader.queryForObject("role.getSystemRole", dto);
		request.setAttribute("roleInfo", roleInfo);
		
		return EDIT_ROLE;
	}
	
	/**
	 * 设置角色权限
	 * @return
	 */
	public  String setRolePermit() {
		try {
			//获取所有功能树结构数据
			String role_code = $("role_id");
			Dto inDto = new BaseDto();
			String listerTreeData = null;
			//获取职位对应的访问权限
			inDto.put("role_id", role_code);
			
			String permit_code = "";
			List<Dto> nList = new ArrayList<Dto>();
			List<Dto> rList = CTReader.queryForList("role.getRolePermits", inDto);
			List<Dto> pList = CTReader.queryForList("role.getAllSystemPermits", inDto);
			if(CTUtils.isNotEmpty(pList)){
				for (Dto dto : pList) {
					permit_code = dto.getAsString("module_id");
					if(StringUtil.checkListExist(rList, "module_id", permit_code)){
						dto.put("checked", "true");
					}else{
						dto.put("checked", "false");
					}
					nList.add(dto);
				}
			}
			if(CTUtils.isNotEmpty(nList)){
				listerTreeData = getFuncTreeJsonData(nList, "module_code", "module_name", "parent_module",request);
			}
			request.setAttribute("listerTreeData", listerTreeData);
			request.setAttribute("role_code", role_code);
			
			return SET_PERMIT;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
	}
	
	
	/**
	 * 增加商户信息
	 * @return
	 */
	public String addCustomer() {
	    //获取下拉数据
		Dto dto = getPraramsAsDto(request);
		request.setAttribute("clevelList", CTUtils.getCodeList("CULEVEL"));
		request.setAttribute("ctype", "add");
		return ADD_CUST;
	}
	
	/**
	 * 修改商户信息
	 * @return
	 */
	public String editCustomer() {
		//获取当前参数
		Dto dto = getPraramsAsDto(request);
		request.setAttribute("ctype", "edit");
		request.setAttribute("clevelList", CTUtils.getCodeList("CULEVEL"));
		Dto customer = (Dto)CTReader.queryForObject("resource.getCustomerInfo", dto);
		request.setAttribute("customerInfo", customer);
		
		return EDIT_CUST;
	}
	
	
	/**
	 * 修改会员信息
	 * @return
	 */
	public String editMemeberInfo() {
		//获取当前参数
		Dto dto = getPraramsAsDto(request);
		Dto memeber = (Dto)CTReader.queryForObject("system.getMemberByID", dto);
		List<Dto> recomList = CTReader.queryForList("system.getMemberInfo");
		request.setAttribute("recomList", recomList);
		request.setAttribute("memeberInfo", memeber);
		return EDIT_MEM;
	}
	
	
	
	/**
	 * 增加用户信息
	 * @return
	 */
	public String addUserInfo() {
	    //获取下拉数据
		Dto dto = getPraramsAsDto(request);
		//获取角色列表
		List<Dto> roleList = CTReader.queryForList("role.getSystemRole");
		request.setAttribute("roleJsonData", getcCommJsonData(roleList, "role_code", "role_name", "0", "true", false, "", true));
		request.setAttribute("userTypeData",getCombJsonData("USERTYPE"));
		
		return ADD_USER;
	}
	
	/**
	 * 修改用户信息
	 * @return
	 */
	public String editUserInfo() {
		//获取当前参数
		Dto dto = getPraramsAsDto(request);
		request.setAttribute("userTypeData",getCombJsonData("USERTYPE"));
		//获取角色列表
		List<Dto> roleList = CTReader.queryForList("role.getSystemRole");
		request.setAttribute("roleJsonData", getcCommJsonData(roleList, "role_code", "role_name", "0", "true", false, "", true));
		Dto userInfo = (Dto)CTReader.queryForObject("system.getUserInfo", dto);
		if(CTUtils.isNotEmpty(userInfo)){
			userInfo.put("password", CTUtils.decryptBasedDes(userInfo.getAsString("password")));
		}
		request.setAttribute("userInfo", userInfo);
		
		return EDIT_USER;
	}
	
	
	/**
	 * 查看用户信息
	 * @return
	 */
	public String seeUserInfo() {
		//获取当前参数
		Dto dto = getPraramsAsDto(request);
		request.setAttribute("userTypeData",getCombJsonData("USERTYPE"));
		
		Dto userInfo = (Dto)CTReader.queryForObject("system.getUserInfo", dto);
		if(CTUtils.isNotEmpty(userInfo)){
			userInfo.put("password", CTUtils.decryptBasedDes(userInfo.getAsString("password")));
			userInfo.put("user_type", getCodeName("USERTYPE", userInfo.getAsString("user_type")));
		}
		request.setAttribute("userInfo", userInfo);
		return SEE_USER;
	}
	
	
	
	/**
	 * 操作用户信息
	 */
	public void operUserInfo() {
		boolean temp = false;
		String err_msg = "false";
		try {
			Dto dto = getPraramsAsDto(request);
			if(CTUtils.isNotEmpty(dto)){
				temp = userInfoService.operUserInfo(dto);
				if(temp){
					if(dto.getAsString("optype").equals("reset_pwd")){
						err_msg = "重置成功，密码为:"+StringUtil.getAttrFromPro("ct_user_password", null);
					}else{
					    err_msg="true";
					}
				}else {
					err_msg="false";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			renderText(err_msg);
		}
	}
	
	/**
	 * 操作角色信息
	 */
	public void operRoleInfo() {
		boolean temp = false;
		String err_msg = "false";
		try {
			Dto dto = getPraramsAsDto(request);
			if(CTUtils.isNotEmpty(dto)){
				temp = userInfoService.operRoleInfo(dto);
				if(temp){
				    err_msg="true";
				}else {
					err_msg="false";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			renderText(err_msg);
		}
	}

	public PageModel getPager() {
		return pager;
	}

	public void setPager(PageModel pager) {
		this.pager = pager;
	}
}
